<template>
  <!-- 视频列表 -->
  <div class="flex flex-col justify-center items-center w-full h-full overflow-y-auto">
    <!-- 加载状态 -->
    <div v-if="videoStore.loading" class="text-white text-center py-4">
      加载中...
    </div>

    <!-- 视频列表 -->
    <div v-else>
      <div v-for="(video, index) in videoStore.videoList" :key="video.id" class="relative w-screen h-screen"
        :ref="(el) => setVideoRef(el)">``
        <!-- VideoItem 组件 -->
        <VideoItem :video="video" class="absolute inset-0 w-full h-full" />

        <!-- VideoActions 组件 -->
        <VideoActions class="absolute right-3 bottom-8 z-10" :video="video" @like="handleLike" @comment="handleComment"
          @favorite="handleFavorite" @share="handleShare" @follow="handleFollow" @user="handleUserProfile" />
      </div>
    </div>

    <!-- 加载更多触发器 -->
    <div v-if="!videoStore.loading && videoStore.hasMore" v-intersection-observer="loadMore" class="h-20"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { useVideoStore } from '@/stores/video'
import VideoItem from './VideoItem.vue'
import VideoActions from './VideoActions.vue'
import type { Video } from '@/services/video/video.types'
import { Toast } from '@kousum/semi-ui-vue'

const videoStore = useVideoStore()

// 动态设置 ref
const setVideoRef = (el: HTMLElement | null) => {
  if (el) {
    // 处理视频元素引用
  }
}

// 加载更多视频s
const loadMore = async ([{ isIntersecting }]: IntersectionObserverEntry[]) => {
  if (isIntersecting) {
    try {
      await videoStore.loadMoreVideos()
    } catch (error) {
      Toast.error('加载更多视频失败')
    }
  }
}

// 处理点赞
const handleLike = (video: Video) => {
  videoStore.updateVideoState(video.id, {
    liked: video.liked,
    like_num: video.like_num
  })
}

// 处理评论
const handleComment = async (video: Video) => {
  try {
    await videoStore.loadComments(video.id)
    // 触发评论弹窗显示
  } catch (error) {
    Toast.error('加载评论失败')
  }
}

// 处理收藏
const handleFavorite = (video: Video) => {
  videoStore.updateVideoState(video.id, {
    favorited: video.favorited,
    favorite_num: video.favorite_num
  })
}

// 处理分享
const handleShare = (video: Video) => {
  videoStore.updateVideoState(video.id, {
    share_num: video.share_num
  })
}

// 处理关注
const handleFollow = (userId: string) => {
  // 更新所有相关视频的作者关注状态
  videoStore.videoList.value
    .filter(v => v.author_id === userId)
    .forEach(v => {
      videoStore.updateVideoState(v.id, {
        is_followed: !v.is_followed
      })
    })
}

// 处理用户主页
const handleUserProfile = (userId: string) => {
  // 导航到用户主页
}

// 初始加载
onMounted(async () => {
  try {
    await videoStore.loadVideos()
  } catch (error) {
    Toast.error('加载视频失败')
  }
})
</script>
